import importlib.util
import json
import logging
import os
import sys
import time

import requests

config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../config.py'))
spec = importlib.util.spec_from_file_location('config', config_path)
config = importlib.util.module_from_spec(spec)
sys.modules['config'] = config
spec.loader.exec_module(config)
DB = config.DB_ZXY

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler("logs/PushQingLiu.log", encoding="utf-8")
    ]
)

# SQL语句
SQL = """
SELECT
    tradeno,
    warehousename,
    flagNames,
    tradestatusexplain,
    shopname
FROM
    j_trade_order_hot
WHERE
    tradestatus IN (1010, 4112)
    AND flagNames LIKE '%转仓发货%'
    AND companyname = '新疆最西域电子商务有限公司'
    AND warehousename NOT IN ('最西域-新疆特产仓')
"""

# 推送接口
PUSH_URL = "https://qingflow.com/api/qsource/ffdc4415-966e-4442-a250-bf7923b0950e"
HEADERS = {"Content-Type": "application/json"}


def load_pushed_tradenos_db():
    conn = None
    tradenos = set()
    try:
        conn = DB()
        with conn.cursor() as cursor:
            cursor.execute("SELECT tradeno FROM pushed_tradenos")
            tradenos = set(row[0] for row in cursor.fetchall())
    except Exception as e:
        logging.error(f"加载已推送订单号失败: {e}")
    finally:
        if conn:
            conn.close()
    return tradenos


def save_pushed_tradeno_db(tradeno, warehousename):
    conn = None
    try:
        conn = DB()
        with conn.cursor() as cursor:
            cursor.execute(
                "INSERT IGNORE INTO pushed_tradenos (tradeno, warehousename) VALUES (%s, %s)",
                (tradeno, warehousename)
            )
            conn.commit()
    except Exception as e:
        logging.error(f"保存已推送订单号失败: {e}")
    finally:
        if conn:
            conn.close()


# 在主循环前加载
pushed_tradenos = load_pushed_tradenos_db()


def fetch_data():
    conn = None
    try:
        conn = DB()
        with conn.cursor() as cursor:
            cursor.execute(SQL)
            columns = [desc[0] for desc in cursor.description]
            results = [dict(zip(columns, row)) for row in cursor.fetchall()]
        return results
    except Exception as e:
        logging.error(f"数据库查询失败: {e}")
        return []
    finally:
        if conn:
            conn.close()


def push_data(data):
    global pushed_tradenos
    if not data:
        logging.info("无数据需要推送")
        return

    new_orders = []
    for item in data:
        tradeno = item.get('tradeno')
        warehousename = item.get('warehousename')
        if not tradeno:
            continue
        if tradeno in pushed_tradenos:
            continue
        new_orders.append(item)

    if not new_orders:
        return

    logging.info(f"发现 {len(new_orders)} 个新订单，开始推送...")
    for item in new_orders:
        tradeno = item.get('tradeno')
        warehousename = item.get('warehousename')
        try:
            print("实际推送内容:", json.dumps(item, ensure_ascii=False, indent=2))
            resp = requests.post(PUSH_URL, headers=HEADERS, data=json.dumps(item), timeout=10)
            if resp.status_code == 200:
                logging.info(f"推送成功，返回: {resp.text}")
                save_pushed_tradeno_db(tradeno, warehousename)
                pushed_tradenos.add(tradeno)
            else:
                logging.error(f"推送失败，状态码: {resp.status_code}，返回: {resp.text}")
        except Exception as e:
            logging.error(f"推送异常: {e}")


def main_loop():
    logging.info("定时监控推送程序启动！")
    while True:
        logging.info("开始查询和推送流程...")
        data = fetch_data()
        push_data(data)
        logging.info("本轮结束，等待4分钟...")
        time.sleep(240)


if __name__ == "__main__":
    try:
        main_loop()
    except Exception as e:
        logging.exception(f"主循环异常退出: {e}")
